package de.mhu.mandalaui.table;

import de.mhu.mandalaui.AbstractComposite;
import de.mhu.mandalaui.Response;
import de.mhu.mandalaui.actions.ClickAction;
import de.mhu.mandalaui.attributes.NamedAttribute;
import de.mhu.mandalaui.text.Text;

public class TableRow extends AbstractComposite<Text,Object> {

	public TableRow() {
	}
	
	public TableRow(ClickAction action, Text ... components ) {
		add(components);
		setClickAction(action);
	}

	public TableRow(String ... names ) {
		for (String name : names) {
			Text col = new Text("");
			col.setBindValue(new NamedAttribute(name));
			add(col,(Object)null);
		}
	}

	public TableRow(Text ... components ) {
		add(components);
	}
	
	public void add(String ... labels) {
		if (labels == null) return;
		for (String label : labels)
			add(new Text(label), (Object)null);
	}
	public void add(Text ... items) {
		if (items == null) return;
		for (Text item : items)
			add(item, (Object)null);
	}

	@Override
	protected void doInitialize() {
		super.doInitialize();
	}

	@Override
	public void render(Response response) {
		
		checkSelectableAction();

		response.startTag("tr", null, this);
		for (Container<Text, Object> item : this) {
			response.startTag(getDataTagName(), null, null);
			response.containerEnter(item.getItem());
			item.getItem().render(response);
			response.containerLeave();
			response.endTag(getDataTagName());
		}
		response.endTag("tr");
	}

	protected void checkSelectableAction() {
		if (getClickAction() == null && getParent() != null && (getParent() instanceof AbstractTable) ) {
			AbstractTable table = (AbstractTable)getParent();
			if (table.getSelectAction() != null) {
				setClickAction(table.getSelectAction());
			}
		}
		
	}

	protected String getDataTagName() {
		return "td";
	}

}
